<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import WebglVue from './views/Webgl.vue'
import ShowList from './views/ShowList.vue'
const deviceForm = ref({
  deviceId: null,
  activStatus: false,
  remainingTime: null,
})
onMounted(() => {
  deviceForm.value = JSON.parse(localStorage.getItem('deviceForm'))
})

const jsonData = ref({})
// ws的部分
// const handleMessage = (event) => {
//   const data = new Uint8Array(event.data)
//   const decoder = new TextDecoder('utf-8')
//   const jsonString = decoder.decode(data).replace(/[\u0000-\u001F\u007F]/g, '')
//   jsonData.value = JSON.parse(jsonString)
// }

const handleWebSocketMessage = (event) => {
  console.log('接收到 WebSocket 消息:', JSON.parse(event.data))
  jsonData.value = JSON.parse(event.data)
}


const connectWebSocket = () => {
  const ip = `ws://${window.location.host}/ws/`
  const socket = new WebSocket(`${ip}obstacles-event`)
  // const socket = new WebSocket(`ws://localhost:8080`)

  socket.binaryType = 'arraybuffer' // 处理二进制数据

  socket.onopen = function () {
    console.log(`事件检测ws服务已经连接: ${ip}obstacles-event`)
  }

  socket.onmessage = handleWebSocketMessage

  socket.onclose = function (event) {
    console.log(`事件检测数据服务断开连接: ${ip}obstacles-event`)
    console.log('断开原因:', event.code)
  }

  socket.onerror = function (error) {
    console.error('WebSocket 错误:', error)
  }
}

const socket = connectWebSocket()

// 卸载
onBeforeUnmount(() => {
  socket?.close()
})


</script>

<template>
  <div class="eventDetection-container">
    <!-- 左边数据展示部分 -->
    <div class="webgl">
      <WebglVue :jsonData="jsonData"></WebglVue>
    </div>

    <!-- 展示数据右边 -->
    <div class="showTable">
      <ShowList :jsonData="jsonData" />
    </div>
  </div>
</template>

<style lang="less" scoped>
.info {
  position: fixed;
  top: 60px;
  right: 20px;
  font-size: 12px;
  line-height: 12px;
}
.eventDetection-container {
  width: 100%;
  height: 100%;
  display: flex;
  box-sizing: border-box;
  padding: 20px;
}

.webgl {
  flex: 1;
  height: 100%;
}

.showTable {
  width: 30%;
}
</style>
